/****************************************************
          File Name:36-3.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Mon 08 Sep 2014 09:13:12 AM CST
*****************************************************/

#include<stdio.h>
#include<sys/resource.h>
#include<errno.h>
#include<stdlib.h>
#include<unistd.h>

void err(char *fun)
{
    perror(fun);
    exit(errno);
}

void sglimit(int resource,int soft,int hard)
{
    struct rlimit lim;

    lim.rlim_cur=soft;     // soft 
    lim.rlim_max=hard;     // hard

    if(setrlimit(resource,&lim)==-1)
        err("setrlimit");

    if(getrlimit(resource,&lim)==-1)
        err("getrlimit");
    else
    {
        printf("The New %s limit is:\n",resource==0?"[CPU]":"[fork]");
        printf("soft: %d; hard: %d\n",lim.rlim_cur,lim.rlim_max);
    }
}

int main(int argc,char *argv[])
{
    if(argc<2)
    {
        printf("%s -time softtime hardtime ]\n",argv[0]);
        printf("or\n");
        printf("%s -fork softtime hardtime ]\n",argv[0]);
        printf("the softtime and hardtime is the new set limit\n");
        exit(1);
    }

    int i,j;

    if(argv[1][1]=='t')
    {
        sglimit(RLIMIT_CPU,atoi(argv[2]),atoi(argv[3]));
        for(i=0;i<200000;i++)
            for(j=0;j<10000;j++);
    }
    if(argv[1][1]=='f')
    {
        sglimit(RLIMIT_NPROC,atoi(argv[2]),atoi(argv[3]));
        for(i=0;;i++)
        {
            pid_t pid;
            switch(pid=fork())
            {
                case -1:
					perror("fork");
                    exit(1);
                case 0:
                    exit(0);
                default:
                    printf("Child %d PID=%d\n",i,pid);
                    break;
            }
        }
    }

    exit(0); // will never run
}
